package chat

import (
	"bufio"
	"log"
	"net"
)

type Client struct {
	conn     net.Conn
	incoming Message
	outgoing Message
	reader   *bufio.Reader
	writer   *bufio.Writer
	quiting  chan net.Conn
	name     string
}

func (client *Client) SetName(name string) {
	client.name = name
}
func (client *Client) Name() string {
	return client.name
}

func (client *Client) Incoming() string {
	return <-client.incoming
}
func (client *Client) SetOutgoing(msg string) {
	client.outgoing <- msg
}

func NewClient(conn net.Conn) *Client {
	writer := bufio.NewWriter(conn)
	reader := bufio.NewReader(conn)

	clt := &Client{
		conn:     conn,
		incoming: make(Message),
		outgoing: make(Message),
		reader:   reader,
		writer:   writer,
		quiting:  make(chan net.Conn),
	}

	clt.listen()
	return clt
}

func (client *Client) listen() {
	go client.Read()
	go client.Write()
}

func (client *Client) Read() {
	for {
		if line, _, err := client.reader.ReadLine(); err == nil {
			client.incoming <- string(line)
		} else {
			log.Printf("Read error : %s\n", err.Error())
			client.quit()
			return
		}
	}
}

func (client *Client) Write() {
	for data := range client.outgoing {
		if _, err := client.writer.WriteString(data + "\n"); err != nil {
			client.quit()
			return
		}
		if err := client.writer.Flush(); err != nil {
			log.Printf("Write error:%s\n", err.Error())
			client.quit()
			return
		}
	}
}

func (client *Client) quit() {
	client.quiting <- client.conn
}
